import Sequelize = require('sequelize');
import { DBManager } from './dbmanager';
import { } from "reflect-metadata"
require("reflect-metadata")

//装饰器


export function dbField()
{
    //属性装饰器
    return function (target: Object, propertyName: string) 
    {

        //又来新状况 Sequelize 不支持es5，必须配置为ES6
        //不知为何 ES6 metadata又正常了
        var t = Reflect.getMetadata("design:type", target, propertyName);
        if (t == null)
        {//非es5 就这么 折腾了
            t = { name: "unknown" };
        }
        var map = target as { [id: string]: any };
        if (map["_fields_"] == undefined)
        {
            map["_fields_"] = {};
        }
        map["_fields_"][propertyName] = t.name;
    }
};

export class ModelAutoReg extends Sequelize.Model
{
    @dbField()
    public id: number = 0;
    @dbField()
    public token: string = "";

    public static RegModel(): void
    {
        var fields = (this.prototype as { [id: string]: any })["_fields_"];
        for (var key in fields)
        {
            console.log("get field:" + key + "=" + fields[key]);
        }
        var attrs: { [id: string]: any } = {};
        var objField: string[] = [];
        for (let key in fields) 
        {
            let type: string = fields[key].toLowerCase();
            if (key == "id")
            {
                attrs[key] = { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true };
                continue;
            }
            if (key == "token")
            {
                attrs[key] = { type: Sequelize.STRING(64)/* , unique: `uq_${this.name}_token` */ };//, primaryKey: true };
                continue;
            }
            else if (key.toLowerCase().indexOf("token") != -1)
            {
                type = "str64";
            }


            let seType: Sequelize.DataType;
            switch (type)
            {
                case "string":
                    seType = Sequelize.TEXT;
                    break;
                case "number":
                    seType = Sequelize.DOUBLE;
                    break;
                case "boolean":
                    seType = Sequelize.BOOLEAN;
                    break;
                case "str64":
                    seType = Sequelize.STRING(64);
                    break;
                case "date":
                    seType = Sequelize.DATE;
                    break;
                default:
                    throw new Error("not support fornow.");
            }

            //默认值 gogogo
            attrs[key] = { type: seType, allowNull: false};//, defaultValue: inst[key] };//inst[key];

        }
        let options={ sequelize: DBManager.getSequlize() };
  
        this.init(attrs,options);
    }
}